/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webshop.backend.dbahif;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;



/**
 *
 * @author MFH
 */
public class DBAdvancedConnectionPool implements DBConfig {

    private final int MAX_CONNECTIONS = 150;
    private int numberCreatedConnections;
    private LinkedList<AdvancedConnection> connections;
    private static DBAdvancedConnectionPool INSTANCE;

    private DBAdvancedConnectionPool() throws ClassNotFoundException {
        connections = new LinkedList<AdvancedConnection>();
        numberCreatedConnections = 0;
        Class.forName(DB_DRIVER);
    }

    public static DBAdvancedConnectionPool getINSTANCE() throws ClassNotFoundException {
        if (INSTANCE == null) {
            INSTANCE = new DBAdvancedConnectionPool();
        }
        return INSTANCE;
    }

    public synchronized AdvancedConnection getConnection() throws SQLException {
        if (connections.isEmpty()) {
            if (numberCreatedConnections < MAX_CONNECTIONS) {
                numberCreatedConnections++;
                return new AdvancedConnection(DriverManager.getConnection(DB_URL + DB_NAME, DB_USER, DB_PASSWD));
            } else {
                throw new SQLException("Please try again later");
            }
        } else {
            return connections.poll();
        }
    }

    public synchronized void releaseConnection(AdvancedConnection ac) {
        if (ac == null) {
            throw new NullPointerException();
        }
        connections.offer(ac);
    }
}
